package playn.game.core;

import static playn.core.PlayN.graphics;
import playn.core.CanvasImage;
import playn.core.GroupLayer;
import playn.core.ImageLayer;
import playn.core.PlayN;

public class SoundManager {

	public GroupLayer layer;
	
	private boolean sound=true;
	private boolean music=true;
	
	public final static String SOUND_BUTTON_ID="Sound";
	public final static String MUSIC_BUTTON_ID="Music";
	
	private ImageLayer soundLayer=null;
	private ImageLayer musicLayer=null;
	
	public Button soundButton=new Button(640-32*2,0,32,32,SOUND_BUTTON_ID);
	public Button musicButton=new Button(640-32  ,0,32,32,MUSIC_BUTTON_ID);
	
	public SoundManager(){
		load();
		soundLayer=graphics().createImageLayer();
		musicLayer=graphics().createImageLayer();
		
		layer=graphics().createGroupLayer();

		layer.addAt(soundLayer, 640-32*2, 0);
		layer.addAt(musicLayer, 640-32, 0);
		
		update();
	}

	private void update(){
		CanvasImage soundImage=graphics().createImage(32, 32);
		CanvasImage musicImage=graphics().createImage(32, 32);

		soundImage.canvas().drawImage(Game.images.get("images.png"), 0, 0, 32, 32,256 , 0, 32, 32);
		musicImage.canvas().drawImage(Game.images.get("images.png"), 0, 0, 32, 32,256 ,32, 32, 32);

		if(!sound){
			soundImage.canvas().drawImage(Game.images.get("images.png"), 0, 0, 32, 32,288 , 0, 32, 32);
		}

		if(!music){
			musicImage.canvas().drawImage(Game.images.get("images.png"), 0, 0, 32, 32,288 , 0, 32, 32);
		}
		
		soundLayer.setImage(soundImage);
		musicLayer.setImage(musicImage);
		
		save();
	}
	
	
	public void sound(){ //switch sound on/off
		if(sound){
			sound=false;
		} else {
			sound=true;
		}
		update();
	}

	public void music() { //switch music on/off
		if(music){
			music=false;
		} else {
			music=true;
		}
		update();
	}
	
	
	private void save(){
		String s=new Boolean(sound).toString();
		String m=new Boolean(music).toString();
		PlayN.storage().setItem(SOUND_BUTTON_ID,s);
		PlayN.storage().setItem(MUSIC_BUTTON_ID,m);

		System.out.println("persistence save {"+SOUND_BUTTON_ID+"="+s+","+MUSIC_BUTTON_ID+"="+m+"}");

	}
	
	private void load(){
		String s=PlayN.storage().getItem(SOUND_BUTTON_ID);
		String m=PlayN.storage().getItem(MUSIC_BUTTON_ID);

		System.out.println("persistence load {"+SOUND_BUTTON_ID+"="+s+","+MUSIC_BUTTON_ID+"="+m+"}");
		
		if(s!=null){
			if(s.equals(new Boolean(false).toString())){
				sound=false;
			}
		}

		if(m!=null){
			if(m.equals(new Boolean(false).toString())){
				music=false;
			}
		}

	}
	
}
